import React, { useState, useEffect, useCallback } from 'react'
import { SideBar, Grid, Image, Ellipsis } from 'antd-mobile'
import { useNavigate, useParams } from 'react-router-dom'
import request, { baseUrl } from '../utils/request'


function Discover() {
    const [tabs, setTabs] = useState([])
    const [datalist, setDatalist] = useState([])

    // 获取动态路由id
    const navigate = useNavigate()
    const { id } = useParams()
    const [activeKey, setActiveKey] = useState(id)

    const getData = () => {
        if (tabs.length === 0) return;
        // 根据id获取分类名称
        const current = tabs.find(item => item._id === activeKey)

        request('/goods', {
            params: {
                category: current.text
            }
        }).then(({ data }) => {
            setDatalist(data.data.result)
        })
    }


    const changeKey = useCallback((key) => {
        setActiveKey(key);

        // ajax请求
        // getData()

        // 切换路由
        // navigate('/discover/' + key)
    }, [])

    const gotoDetail = useCallback((id) => {
        navigate('/goods?id=' + id)
    }, [])

    // 获取分类数据
    useEffect(() => {
        request('/category').then(({ data }) => {
            const tabs = data.data.result
            setTabs(tabs)

            setActiveKey(tabs[0]._id)


        })
    }, [])

    // 根据id不同请求不同的数据
    useEffect(() => {
        getData()
    }, [activeKey, tabs])

    return <div style={{ margin: '-1em', height: '100%' }}>
        <SideBar activeKey={activeKey} onChange={changeKey}>
            {tabs.map(item => (
                <SideBar.Item key={item._id} title={item.text} />
            ))}
        </SideBar>
        <div className='goodslist'>
            <Grid columns={2} gap={18}>
                {
                    datalist.map(item => (
                        <Grid.Item key={item._id} onClick={gotoDetail.bind(null, item._id)}>
                            <Image src={baseUrl + item.img_url} width="100%" />
                            <Ellipsis content={item.goods_name} rows={3} expandText="展开" collapseText="收起">

                            </Ellipsis>

                            <p className='price'><del>{item.price}</del><span>{item.sales_price}</span></p>
                        </Grid.Item>

                    ))
                }
            </Grid>
        </div>


    </div>
}

export default Discover;